import api from './api.js';

export default {
  template: `
    <div>
      <el-table :data="cartData" style="width: 100%">
        <el-table-column prop="name" label="菜名"></el-table-column>
        <el-table-column prop="quantity" label="数量">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity" @change="editItem(scope.$index, scope.row)" :min="1"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="总价">
          <template #default="scope">
            ¥{{ scope.row.price * scope.row.quantity }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" @click="deleteItem(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="order-footer">
        <div class="total-price">总价：¥{{ totalPrice }}</div>
        <el-button type="primary" @click="checkout">结算</el-button>
      </div>
    </div>
  `,
  props: ['userInfo', 'isLoggedIn'],
  data() {
    return {
      orderId: 0,
      cartData: [],
    };
  },
  async created() {
    if (this.isLoggedIn) {
      try {
        const response = await api.getOrdersByStatus(this.userInfo.id, 1);
        if (response.data.data) {
          this.orderId = response.data.data[0].orderId;
        } else {
          const createOrderResponse = await api.createOrder(this.userInfo.id);
          this.orderId = createOrderResponse.data.data.orderId;
        }
      } catch (error) {
        console.error(error);
      }
      const resp = await api.getOrderDishes(this.orderId);
      this.cartData = resp.data.data;
    }
  },
  methods: {
    async editItem(index, row) {
      try {
        await api.updateOrderDish(this.orderId, row.dishId, row.quantity);
      } catch (error) {
        console.error(error);
      }
    },
    async deleteItem(index, row) {
      try {
        await api.deleteOrderDish(this.orderId, row.dishId);
        this.cartData.splice(index, 1);
      } catch (error) {
        console.error(error);
      }
    },
    async checkout() {
      try {
        await api.updateOrderStatus(this.orderId, 0);
        this.cartData = [];
        const createOrderResponse = await api.createOrder(this.userInfo.id);
        this.orderId = createOrderResponse.data.data.orderId;
        this.$message.success('结算成功，购物车已清空');
      } catch (error) {
        this.$message.error('结算失败');
      }
    }
  },
  computed: {
    totalPrice() {
      return this.cartData.reduce((total, item) => total + item.quantity * item.price, 0);
    }
  }
};
